﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Rhonin.Common.Components;
using Rhonin.Common.Entity.Api;
using Rhonin.Common.Entity.Exception;
using Rhonin.Common.Logging;
using Rhonin.Common.Utilities;
using System.Collections.Generic;

namespace ApiManage.Svc.Filter
{
    /// <inheritdoc />
    /// <summary>
    /// 统一错误信息返回
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly ILogger _log = ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(ApiExceptionFilterAttribute));
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            var dictionary = new Dictionary<string, object>();
            foreach (var key in context.ModelState.Keys)
            {
                dictionary[key] = context.ModelState[key].RawValue;
            }

            var apiResult = new ApiResult
            {
                Status = ResultStatus.Exception,
                Server = IpUtils.GetHostIp(),
                Message = context.Exception.Message
            };

            if (context.Exception is ApiException)
            {
                apiResult.Status = ResultStatus.Fail;
            }
            else
            {
                var message = $"异常信息为：【{context.Exception}】参数信息:【{JsonConvert.SerializeObject(dictionary)}】";
                _log.Error(message);

            }
            context.Result = new JsonResult(apiResult);
        }
    }
}
